package it.ap.sa.core.utils;

import java.net.Authenticator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Classe di controllo per la connessione al proxy
 */
@Service
public class ProxyUtil {

	private static final Logger logger = LoggerFactory.getLogger(ProxyUtil.class.getName());

	@Autowired
	private CoreProperties prop;

	/**
	 * Inizializza le proprieta' del sistema per la connessione al proxy.
	 */
	public void initSystemProxyConnection() {
		try {

			/**** Proxy ****************************************/
			if (prop.proxyActive) {

				System.setProperty("http.proxyHost", prop.proxyHost);
				System.setProperty("http.proxyPort", String.valueOf(prop.proxyPort));
				System.setProperty("http.proxyUser", prop.proxyUsername);
				System.setProperty("http.proxyPassword", prop.proxyPassword);
				System.setProperty("http.nonProxyHosts", prop.nonProxyHosts);

				System.setProperty("https.proxyHost", prop.proxyHost);
				System.setProperty("https.proxyPort", String.valueOf(prop.proxyPort));
				System.setProperty("https.proxyUser", prop.proxyUsername);
				System.setProperty("https.proxyPassword", prop.proxyPassword);
				System.setProperty("https.nonProxyHosts", prop.nonProxyHosts);

				if (prop.proxyHost != null && !prop.proxyHost.equals("")) {
					if (prop.proxyUsername != null && !prop.proxyUsername.equals("") && prop.proxyPassword != null && !prop.proxyPassword.equals(""))
						Authenticator.setDefault(new ProxyAuthenticator(prop.proxyUsername, prop.proxyPassword));
				}

				logger.info(">>>>>>>>>>>>>>>>>>>>> PROXY ABILITATO >>>>>>>>>>>>>>>>>>>>>>>>>>>>><");
			} else
				logger.info(">>>>>>>>>>>>>>>>>>>>> PROXY NON ABILITATO >>>>>>>>>>>>>>>>>>>>>>>>>>>>><");

			/***************************************************/
		} catch (Exception e) {
			logger.error("Errore nell 'impostare i dati del proxy " + e, e);
			throw (e);
		}
	}
}
